package com.fire.user.util;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.QuerySendDetailsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.QuerySendDetailsResponse;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.fire.core.service.ITMitServiceDicBaseServices;
import com.fire.user.constants.AliConstants;
import com.fire.user.service.ITMitServiceDicBaseService;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author yuanchong
 * 调用阿里云短信API
 * 工程依赖了2个jar包
 * 1:aliyun-java-sdk-core.jar
 * 2:aliyun-java-sdk-dysmsapi.jar
 */
@Component
public class AliyunSmsUtil {
	private static Logger logger = Logger.getLogger(AliyunSmsUtil.class);

    @Autowired
    private ITMitServiceDicBaseServices baseServices;

	/**
	 * 产品名称:云通信短信API产品,开发者无需替换
	 * Dysmsapi
	 */
    private String product = "";
    /**
     * 产品域名,开发者无需替换
     * dysmsapi.aliyuncs.com
     */
    private String domain = "";
    /**
     * Access Key ID
     * LTAIsKA8rRem3uwV
     */
    private String accessKeyId = "";
    /**
     * Access Key Secret
     * aTqO9mapT11n8P8UeZhRux35yrzzPT
     */
    private String accessKeySecret = "";
    /**
     * 短信模板ID
     * SMS_130970040
     */
    private String templateCode = "";
    /**
     * 签名名称
     * 袁冲
     */
    private String signName = "";
    /**
     * regionId
     * cn-hangzhou
     */
    private String regionId = "";
    /**
     * endPointName
     * cn-hangzhou
     */
    private String endPointName = "";
    
    /**
     * 获取配置信息
     * */
    public void getConfigure(){
    	product = baseServices.getBaseByBkey(AliConstants.ALI_SMS_PRODUCT);
    	domain = baseServices.getBaseByBkey(AliConstants.ALI_SMS_DOMAIN);
    	accessKeyId = baseServices.getBaseByBkey(AliConstants.ALI_SMS_ACCESSKEYID);
    	accessKeySecret = baseServices.getBaseByBkey(AliConstants.ALI_SMS_ACCESSKEYSECRET);
    	templateCode = baseServices.getBaseByBkey(AliConstants.ALI_SMS_TEMPLATECODE);
    	signName = baseServices.getBaseByBkey(AliConstants.ALI_SMS_SIGNNAME);
    	regionId = baseServices.getBaseByBkey(AliConstants.ALI_SMS_REGIONID);
    	endPointName = baseServices.getBaseByBkey(AliConstants.ALI_SMS_REGIONID);
        /*TMitServiceDicBase baseInfo = baseService.selectById(AliConstants.ALI_SMS_PRODUCT);
        if (baseInfo!=null){
        	product= baseInfo.getBvalue().trim();
        }

        TMitServiceDicBase baseInfo1 = baseService.selectById(AliConstants.ALI_SMS_DOMAIN);
        if (baseInfo1!=null){
        	domain=baseInfo1.getBvalue().trim();
        }

        TMitServiceDicBase baseInfo2 = baseService.selectById(AliConstants.ALI_SMS_ACCESSKEYID);
        if (baseInfo2!=null){
        	accessKeyId=baseInfo2.getBvalue().trim();
        }
        
        TMitServiceDicBase baseInfo3 = baseService.selectById(AliConstants.ALI_SMS_ACCESSKEYSECRET);
        if (baseInfo3!=null){
        	accessKeySecret=baseInfo3.getBvalue().trim();
        }
        
        TMitServiceDicBase baseInfo4 = baseService.selectById(AliConstants.ALI_SMS_TEMPLATECODE);
        if (baseInfo4!=null){
        	templateCode=baseInfo4.getBvalue().trim();
        }
        
        TMitServiceDicBase baseInfo5 = baseService.selectById(AliConstants.ALI_SMS_SIGNNAME);
        if (baseInfo5!=null){
        	signName=baseInfo5.getBvalue().trim();
        }
        
        TMitServiceDicBase baseInfo6 = baseService.selectById(AliConstants.ALI_SMS_REGIONID);
        if (baseInfo6!=null){
        	regionId=baseInfo6.getBvalue().trim();
        	endPointName=baseInfo6.getBvalue().trim();
        }*/
    }

    /**
     * 发送短信
     * @param accessKeyId   此处需要替换成开发者自己的AK(在阿里云访问控制台寻找)
     * @param accessKeySecret
     * @param phoneNumber   待发送手机号
     * @param templateCode  短信模板号
     * @param signName      短信签名
     * @param outId         自定义短信回执ID
     * @return
     * @throws ClientException
     */
    public SendSmsResponse sendSms(String phoneNumber,String paramStr) throws Exception {
    	 logger.info("sendSms:phoneNumber="+phoneNumber+",paramStr="+paramStr);
        //可自助调整超时时间
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");

        //初始化acsClient,暂不支持region化
        IClientProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, accessKeySecret);
        DefaultProfile.addEndpoint(endPointName, regionId, product, domain);
        IAcsClient acsClient = new DefaultAcsClient(profile);
        
        //组装请求对象-具体描述见控制台-文档部分内容
        SendSmsRequest request = new SendSmsRequest();
        //必填:待发送手机号
        request.setPhoneNumbers(phoneNumber);
        //必填:短信签名-可在短信控制台中找到
        request.setSignName(signName);
        //必填:短信模板-可在短信控制台中找到
        request.setTemplateCode(templateCode);
        //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
        request.setTemplateParam(paramStr);
        //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
        String outId = phoneNumber + System.currentTimeMillis();
        request.setOutId(outId);

        //hint 此处可能会抛出异常，注意catch
        SendSmsResponse aliResponse = acsClient.getAcsResponse(request);
        return aliResponse;
    }

    /**
     * 查询发送短信明细
     * @param bizId
     * @param accessKeyId
     * @param accessKeySecret
     * @param phoneNumber
     * @return
     * @throws ClientException
     */
    public QuerySendDetailsResponse querySendDetails(String bizId,String accessKeyId,
    		String accessKeySecret,String phoneNumber) throws ClientException {
        //可自助调整超时时间
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");

        //初始化acsClient,暂不支持region化
        IClientProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, accessKeySecret);
        DefaultProfile.addEndpoint(endPointName, regionId, product, domain);
        IAcsClient acsClient = new DefaultAcsClient(profile);

        //组装请求对象
        QuerySendDetailsRequest request = new QuerySendDetailsRequest();
        //必填-号码
        request.setPhoneNumber(phoneNumber);
        //可选-流水号
        request.setBizId(bizId);
        //必填-发送日期 支持30天内记录查询，格式yyyyMMdd
        SimpleDateFormat ft = new SimpleDateFormat("yyyyMMdd");
        request.setSendDate(ft.format(new Date()));
        //必填-页大小
        request.setPageSize(10L);
        //必填-当前页码从1开始计数
        request.setCurrentPage(1L);

        //hint 此处可能会抛出异常，注意catch
        QuerySendDetailsResponse querySendDetailsResponse = acsClient.getAcsResponse(request);

        return querySendDetailsResponse;
    }

    public static void main(String[] args) throws Exception {
    	AliyunSmsUtil util = new AliyunSmsUtil();
        //发短信
        SendSmsResponse response = util.sendSms(
        		"15018527400","{\"name\":\"AndyLau\", \"code\":\"888888\"}");
        System.out.println("短信接口返回的数据----------------");
        System.out.println("Code=" + response.getCode());
        System.out.println("Message=" + response.getMessage());
        System.out.println("RequestId=" + response.getRequestId());
        System.out.println("BizId=" + response.getBizId());

        Thread.sleep(3000L);

        //查明细
        if(response.getCode() != null && 
        	AliConstants.ALI_SMS_REQ_SUCCESS.equals(response.getCode())) {
            QuerySendDetailsResponse querySendDetailsResponse = 
            		util.querySendDetails(
            				response.getBizId(),"LTAIsKA8rRem3uwV",
            				"aTqO9mapT11n8P8UeZhRux35yrzzPT","15018527400");
            System.out.println("短信明细查询接口返回数据----------------");
            System.out.println("Code=" + querySendDetailsResponse.getCode());
            System.out.println("Message=" + querySendDetailsResponse.getMessage());
            int i = 0;
            for(QuerySendDetailsResponse.SmsSendDetailDTO smsSendDetailDTO : querySendDetailsResponse.getSmsSendDetailDTOs())
            {
                System.out.println("SmsSendDetailDTO["+i+"]:");
                System.out.println("Content=" + smsSendDetailDTO.getContent());
                System.out.println("ErrCode=" + smsSendDetailDTO.getErrCode());
                System.out.println("OutId=" + smsSendDetailDTO.getOutId());
                System.out.println("PhoneNum=" + smsSendDetailDTO.getPhoneNum());
                System.out.println("ReceiveDate=" + smsSendDetailDTO.getReceiveDate());
                System.out.println("SendDate=" + smsSendDetailDTO.getSendDate());
                System.out.println("SendStatus=" + smsSendDetailDTO.getSendStatus());
                System.out.println("Template=" + smsSendDetailDTO.getTemplateCode());
            }
            System.out.println("TotalCount=" + querySendDetailsResponse.getTotalCount());
            System.out.println("RequestId=" + querySendDetailsResponse.getRequestId());
        }
    }

	public String getProduct() {
		return product;
	}

	public void setProduct(String product) {
		this.product = product;
	}

	public String getDomain() {
		return domain;
	}

	public void setDomain(String domain) {
		this.domain = domain;
	}

	public String getAccessKeyId() {
		return accessKeyId;
	}

	public void setAccessKeyId(String accessKeyId) {
		this.accessKeyId = accessKeyId;
	}

	public String getAccessKeySecret() {
		return accessKeySecret;
	}

	public void setAccessKeySecret(String accessKeySecret) {
		this.accessKeySecret = accessKeySecret;
	}

	public String getTemplateCode() {
		return templateCode;
	}

	public void setTemplateCode(String templateCode) {
		this.templateCode = templateCode;
	}

	public String getSignName() {
		return signName;
	}

	public void setSignName(String signName) {
		this.signName = signName;
	}

	public String getRegionId() {
		return regionId;
	}

	public void setRegionId(String regionId) {
		this.regionId = regionId;
	}

	public String getEndPointName() {
		return endPointName;
	}

	public void setEndPointName(String endPointName) {
		this.endPointName = endPointName;
	}
}
